package main

import (
	"fmt"
	"google.golang.org/grpc"
	"gosecond/ch16grpc/streamgrpc/proto"
	"net"
	"sync"
	"time"
)

const PORT = "0.0.0.0:50052"

type Server struct {
}

func (s *Server) GetStream(req *proto.StreamReqData, res proto.Greeter_GetStreamServer) error {
	i := 0
	for {
		i++
		_ = res.Send(&proto.StreamResData{
				Data: fmt.Sprintf("%v", time.Now().Unix()),
			})
		time.Sleep(time.Second * 1)
		if i > 10 {
			break
		}
	}
	return nil
}
func (s *Server) PutStream(cliStr proto.Greeter_PutStreamServer) error {
	for {
		if a, err:=cliStr.Recv();err!=nil{
			fmt.Println(err)
			break
		}else{
			fmt.Println(a.Data)
		}
	}
	return nil
}
func (s *Server) AllStream(allStr proto.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)
	//接受数据
	go func() {
		defer wg.Done()
		for {
			data, _ := allStr.Recv()
			fmt.Println("收到客户端消息：", data.Data)
		}
	}()

	//发送数据
	go func() {
		defer wg.Done()
		for {
			_ = allStr.Send(&proto.StreamResData{
				Data: "我是服务器",
			})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()

	return nil
}
func main() {
	g := grpc.NewServer()
	proto.RegisterGreeterServer(g, &Server{})

	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		panic("fail to listen: " + err.Error())
	}
	err = g.Serve(lis)
	if err != nil {
		panic("fail to start grpc")
	}
}
